package lion.framework.core.conf.loader;

import java.io.FileOutputStream;
import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import lion.dev.lang.MapJ;
import lion.framework.core.conf.Config;
import lion.framework.core.conf.IConfigLoader;
import lion.framework.core.conf.anno.ConfigLoader;

/**
 * this config loader read the property file <br/>
 * the file path must under classpath
 *
 * <pre>
 * time   2013 2013年12月11日 下午4:19:44
 * mail   hl_0074@sina.com
 * </pre>
 *
 * @author lion
 */
@ConfigLoader("property")
public class PropertyConfigLoader implements IConfigLoader {

	private String path;
	private static Log log = LogFactory.getLog(PropertyConfigLoader.class);

	public PropertyConfigLoader(MapJ param) {

		this(param.getString("file"));
	}

	public PropertyConfigLoader(String file) {

		this.path = file;
	}

	@Override
	public Map<String, Object> load() throws Exception {

		Properties properties = new Properties();
		try {
			properties.load(PropertyConfigLoader.class.getClassLoader().getResourceAsStream(path));
		} catch (Exception e) {
			log.error("properties file [" + path + "] not found");
		}
		Map<String, Object> result = new HashMap<>();
		for (Enumeration<Object> e = properties.keys(); e.hasMoreElements();) {
			String key = (String) e.nextElement();
			result.put(key, properties.getProperty(key));
		}
		return result;
	}

	@Override
	public void save(Config conf) throws Exception {

		Properties properties = new Properties();
		for (String key : conf.keySet()) {
			properties.put(key, conf.get(key));
		}

		try (FileOutputStream fos = new FileOutputStream(URLDecoder.decode(PropertyConfigLoader.class.getClassLoader().getResource(path).getPath(), "UTF-8"))) {
			properties.store(fos, "");
		} catch (Exception e) {
			log.error("failed to store config", e);
		}
	}

	@Override
	public <T> T select(String arg) {

		throw new RuntimeException("operation not support in property config loader");
	}

}
